/**
 * 照片 模型。包含明星与普通用户的照片。
 */
const constants = require('../../utils/constants');
const models = require('../../utils/models');

module.exports = class Withdraw extends think.Model {
    get tableName() {
        return 'photo';
    }

    /**
     * 获取一张照片记录。
     */
    async getOne(id) {
        return this.where({id: id}).find();
    }

    /**
     * 根据百度uid获取照片。
     */
    async getOneByBid(bid) {
        return this.where({bid: bid}).find();
    }

    /**
     * 保存用户照片（脸型）。
     */
    async createOne(data, uploadPhotoToStorage) {
        try {
            // 保存记录
            const photo = {
                userId: data.userId,
                userName: data.userName || null,
                photoType: data.photoType,
                bid: data.bid,
                bUserInfo: data.bUserInfo,
                photoPath: data.localFilePath,
                photoUrl: data.photoUrl
            };
            photo.id = await this.add(photo, {});

            // 上传照片，异步进行
            if (uploadPhotoToStorage) {
                this.uploadToNetStorage(photo.userId, photo.photoPath, photo.id, photo.photoType);
            }

            return photo;
        } catch (err) {
            think.logger.error(`用户照片保存失败: ` + err.message);

            return null;
        }
    }

    /**
     * 上传至网络存储。
     */
    async uploadToNetStorage(userId, localFileName, photoId, photoType) {
        try {
            const photoGroup = photoType === constants.PhotoType.Star ? 'stars' : 'general';
            const simpleFileName = localFileName.substring(localFileName.lastIndexOf('/') + 1);
            const remoteFileName = `${photoGroup}/${userId}/${simpleFileName}`;

            const storageModel = think.model(models.Storage);
            const photoUrl = await storageModel.uploadFile(localFileName, remoteFileName, false);
            this.where({id: photoId}).update({photoUrl: photoUrl});
        } catch(err) {
            think.logger.error('保存用户照片至网络存储出错: ' + err.message);
        }
    }
};
